package com.matrix.rabbitmqtest.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者
 */
public class Consumer {
    public static final String QUEUE_NAME = "BUFFER";

    public static void main(String[] args) throws IOException, TimeoutException {
        // 连接到MQ
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        Connection connection = connectionFactory.newConnection();
        // 从连接中获取信道
        Channel channel = connection.createChannel();
        // 设置接收消息的回调
        DeliverCallback deliverCallback = (consumerTag,msg) -> {
            System.out.println("接收到消息"+new String(msg.getBody()));
        };
        // 取消消息的回调
        CancelCallback cancelCallback = consumerTag -> {
            System.out.println("consumerTag:"+consumerTag+"取消消息回调");
        };
        // 开始接收
        // 参数: 路由(队列名), 消费成功自动回复, 接收回调, 取消回调
        channel.basicConsume(QUEUE_NAME,true,deliverCallback,cancelCallback);

    }
}
